<template>
    <van-popup v-model:show="visible" position="bottom" class="popup-container">
        <div class="popup-header">
            <h3 class="popup-title">
                {{ props.title }}附件列表
            </h3>
        </div>
        <div class="attachment-list">
            <div v-if="!props.attachments || props.attachments.length === 0" class="no-attachment">
                <van-empty description="暂无附件" />
            </div>
            <van-cell v-for="(item, index) in props.attachments" :key="index" :title="item.name + item.subFix"
                :value="formatFileSize(item.size)" @click="handleDownload(item)">
            </van-cell>
        </div>
    </van-popup>
</template>
<script setup>
import { ref } from 'vue';
import fileAPI from "@/api/file";
import { errorNotify } from "@/utils/Misc";
const props = defineProps(["attachments", "title"]);
const visible = ref(false);
const formatFileSize = (bytes) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};
const handleDownload = async (file) => {
    try {
        const res = await fileAPI.downloadFile(file.id);
        const blob = new Blob([res.data], { type: res.headers['content-type'] });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        let filename = file.name + file.subFix;
        const disposition = res.headers['content-disposition'];
        if (disposition) {
            const match = disposition.match(/filename="(.+)"/);
            if (match && match[1]) {
                filename = match[1];
            }
        }
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    } catch (error) {
        errorNotify("FileList.vue", "handleDownload", error)
    }
};
const showFileList = () => {
    visible.value = true;
};
defineExpose({
    showFileList,
})
</script>
<style scoped>
.popup-container {
    min-height: 20vh;
    max-height: 70vh;
    display: flex;
    flex-direction: column;
}

.popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-bottom: 1px solid #f5f5f5;
    flex-shrink: 0;
}

.popup-title {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: #333;
}

.close-icon {
    font-size: 20px;
    color: #999;
}

.attachment-list {
    flex-grow: 1;
    overflow-y: auto;
    padding-top: 10px;
}

.no-attachment {
    padding: 50px 0;
    text-align: center;
}
</style>
